﻿using System;
using System.Collections.Generic;
using System.Linq;
using Ross.EntityFramework;
using Ross.EntityFramework.Model;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using System.Linq.Expressions;

namespace Ross.Service
{
    public class CommentsService : BaseService, IDisposable
    {
        private TranDbContext dbContext;
        public IRepository<Comments, long> repository;

        public CommentsService(string nameOrConnectionString)
        {
            dbContext = new TranDbContext(nameOrConnectionString);
            repository = new Repository<Comments, long>(dbContext);
        }
        public void Dispose()
        {
            dbContext.Dispose();
        }

        //添加
        public ResultDto<bool> Comment(Dto.Comments comments)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                var model = Mapper.Map<Comments>(comments);
                repository.Insert(model);
                result.status = 200;
                result.datas = true;
            }
            catch(Exception ex) {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        }

        //获取列表
        public ResultDto<List<Dto.Comments>> GetAllList(string keywords = "", long userId = 0, long courseId = 0)
        {
            ResultDto<List<Dto.Comments>> result = new ResultDto<List<Dto.Comments>>();
            Expression<Func<Comments, bool>> expression = o => o.ID > 0;
            if (!string.IsNullOrEmpty(keywords))
                expression = expression.ExpressionAnd(t => t.Contents.Contains(keywords));
            if (userId != 0)
                expression = expression.ExpressionAnd(t => t.UserID == userId);
            if (courseId != 0)
                expression = expression.ExpressionAnd(t => t.CourseID == courseId);
            var lists = repository.GetAllList(expression);
            result.datas = Mapper.Map<List<Dto.Comments>>(lists);
            return result;
        }
        //删除
        public ResultDto<bool> Delete(long id)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                repository.Delete(id);
                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        }
    }
}
